import type {ModalFormProps} from "@ant-design/pro-form/lib/layouts/ModalForm";
import CModalForm from "@/components/CModalForm";
import type {CModalFormProps} from "@/components/CModalForm/type";
import fields from "@/pages/system/role/list/components/AddSysRole/config/fields";
import SysRoleMenu from "@/pages/system/role/list/components/AddSysRole/components/SysRoleMenu";
import type {TreeProps} from "antd";
import React, {useEffect, useState} from "react";
import {buttonAuthorizeList, sysMenuPageList} from "@/services/system/menu/api";
import type {SysMenuData} from "@/pages/system/menu/type";
import {Col, Divider, Row} from 'antd';


export default (props: {} & ModalFormProps) => {
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>(props.initialValues?.roleMenuList.map((item: any) => item.menuId));
  const [checkedButtonKeys, setCheckedButtonKeys] = useState<React.Key[]>([]);
  const [treeData, setTreeData] = useState<any[]>([]);
  const [treeButtonData, setTreeButtonData] = useState<any[]>([]);
  useEffect(() => {
    sysMenuPageList({}).then(res => {
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      setTreeData(processTreeData(res.data))
      setCheckedButtonKeys(props.initialValues?.roleMenuList.filter((item: any) => !item.menu).map((item: any) => item.menuId));
    })
    buttonAuthorizeList(checkedKeys).then(res =>{
      setTreeButtonData(processTreeData(res.data))
    })
  }, [])


  const processTreeData = (sysMenuDataList: SysMenuData[]): any[] => {
    if (!sysMenuDataList) {
      return [];
    }
    return sysMenuDataList.map(item => {
      return {
        key: item.id,
        title: item.menuName,
        children: processTreeData(item.children)
      }
    })
  }


  const onCheck = (checkedKeysValue: React.Key[]) => {
    buttonAuthorizeList(checkedKeysValue).then(res =>{
      setTreeButtonData(processTreeData(res.data))
    })
    setCheckedKeys(checkedKeysValue);
  };

  const onButtonCheck = (checkedKeysValue: React.Key[]) => {
    setCheckedButtonKeys(checkedKeysValue);
  };


  // @ts-ignore
  const modalFormProps: CModalFormProps<any> = {
    ...props,
    groupList: fields,
    onFinish: (formData) => {
      debugger
      let data = { ...formData, menuIds: [...checkedKeys] }
      // @ts-ignore
      return props.onFinish(data);
    }
  }

  const roleMenuProps: {} & TreeProps = {
    // @ts-ignore
    onCheck,
    checkedKeys,
    treeData,
    defaultExpandAll: true
  }

  const roleButtonProps: {} & TreeProps = {
    // @ts-ignore
    onButtonCheck,
    checkedButtonKeys,
    treeData: treeButtonData,
    defaultExpandAll: true
  }
  return (
    <CModalForm{...modalFormProps}>
      <Row >
        <Col span={"12"}>
          <Divider orientation={"left"}> 角色权限</Divider>
          <SysRoleMenu {...roleMenuProps}/>
        </Col>
      </Row>
    </CModalForm>
  )
}
